package org.huntaway.kindergarten.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.huntaway.kindergarten.po.SysUser;

public class UserCheckFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		log(httpRequest.getRequestURI() + ":" + httpRequest.getRemoteHost()
				+ ":" + httpRequest.getLocalAddr());
		String url = httpRequest.getRequestURI();
		try {
			HttpSession session = httpRequest.getSession(true);
			SysUser uib = (SysUser) session.getAttribute("user");
			if (check(url)) {
				chain.doFilter(httpRequest, httpResponse);
				return;
			}
			if (url.endsWith(".do") || url.endsWith("/")) {
				if (uib == null) {
					if (url.endsWith("login.do")) {
						chain.doFilter(httpRequest, httpResponse);
						return;
					} else {
						RequestDispatcher dispatcher = request
								.getRequestDispatcher("/login.do");
						dispatcher.forward(request, response);
						return;
					}
				}
			}
			chain.doFilter(request, response);
		} catch (IOException e) {
		} catch (ServletException e) {
		}
	}

	private boolean check(String url) {
		if (url.endsWith(".css") || url.endsWith(".js") || url.endsWith(".jpg")
				|| url.endsWith(".png")) {
			return true;
		}
		return false;
	}

	private void log(String str) {
		System.out.println(str);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		log(UserCheckFilter.class.getName() + " init is run...");
	}
}
